//
//  ViewController.m
//  19-JSON-WYNews
//
//  Created by 王道林 on 16/8/9.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "ViewController.h"
#import "NewsTitle.h"
#import "NewsTitleCollectionViewCell.h"
#import "CustomLayout.h"
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, CustomLayoutDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *newsArray;
@property (nonatomic, strong) CustomLayout *layout;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _layout = (CustomLayout *)self.collectionView.collectionViewLayout;
    _layout.delegate = self;
    [self handleData];
    
}

- (void)handleData
{
    _newsArray = [NSMutableArray array];
   NSString *newsJson = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
    NSData *JSONData = [NSData dataWithContentsOfFile:newsJson];
    
    // JSON 解析
    NSError *error = nil;
   NSDictionary *JSONDic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
    
    NSArray *list = JSONDic[@"tList"];
    for (NSDictionary *dic in list) {
        NewsTitle *news = [NewsTitle newsTitleWithDic:dic];
        [_newsArray addObject:news];
    }
    
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _newsArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewsTitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"wang" forIndexPath:indexPath];
    NewsTitle *newTitle = _newsArray[indexPath.row];
    cell.newsTitle = newTitle;
    return cell;
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewsTitle *newTitle = _newsArray[indexPath.row];
    NSString *string = newTitle.tname;
    
    CGRect rect = [string boundingRectWithSize:CGSizeMake(0, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    
    CGFloat width = ceilf(CGRectGetWidth(rect));
    return width;
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
